package com.rich.login.controller;

import com.rich.common.constant.Broker;
import com.rich.common.entity.TbBroker;
import com.rich.common.result.CommonResponse;
import com.rich.common.util.JwtUtil;
import com.rich.login.mapper.BrokerMapper;
import com.rich.login.service.BrokerService;
import com.rich.login.vo.BrokerPhoneLoginVo;
import com.rich.login.vo.BrokerPwdLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author:张龙飞
 * @Date:2021/8/14
 */
@RestController
@RequestMapping("/brokerLogin")
@Slf4j
public class BrokerController {

    @Autowired
    private BrokerService brokerService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private BrokerMapper brokerMapper;
    /**
     *@描述   经纪人手机号验证码登录
     *@参数  [userLoginVo]
     *@返回值  com.coco.common.result.CommonResponse
     *@创建人  zhanglongfei
     *@创建时间  2021/8/13
     *@修改人和其它信息
     */
    @PostMapping("/dologinYzm")
    public CommonResponse dologin(@RequestBody BrokerPhoneLoginVo userLoginVo){
        return brokerService.dologin(userLoginVo);
    }

    /**
     *  经纪人账号密码登录
     *
     */
    @PostMapping("dologinPwd")
    public CommonResponse dologinPwd(@RequestBody BrokerPwdLoginVo brokerPwdLoginVo, HttpServletResponse response){
        TbBroker broker=  brokerMapper.findByPhone(brokerPwdLoginVo.getPhone());
        if (broker!=null){
            if (broker.getPassword().equals(brokerPwdLoginVo.getPassword())){
                //登陆成功
                String uuid = UUID.randomUUID().toString();
                String loginToken = uuid.replace("-", "");
                String token= JwtUtil.createToken(loginToken,new Date());
                System.out.println(loginToken);
                log.info(token);
                Cookie cookie = new Cookie("token",token);
                response.addCookie(cookie);
                redisTemplate.opsForValue().set(loginToken,broker,30, TimeUnit.MINUTES);
                return new CommonResponse(Broker.BROKER_LOGIN_SUCCESS,Broker.BROKER_LOGIN_SUCCESS_MESSAGE,token);
            }else {
                return new CommonResponse(Broker.BROKER_PWD_ERROR,Broker.BROKER_PWD_ERROR_MESSAGE);
            }
        }
        return new CommonResponse(Broker.USER_EXIST_CODE,Broker.USER_EXIST_MESSAGE);
    }

    @RequestMapping("/getLoginBroker")
    @ResponseBody
    public TbBroker getLoginBroker(@RequestParam("token")String token){
        String s = JwtUtil.parseToken(token);
        TbBroker o = (TbBroker) redisTemplate.opsForValue().get(s);
        System.out.println(o);
        return o;
    }
}
